package city.spring.modules.sitting.controller;

import city.spring.modules.oldman.entity.OldmanInfoEntity;
import city.spring.modules.oldman.service.OldmanInfoService;
import city.spring.modules.sitting.entity.SittingRecordEntity;
import city.spring.modules.sitting.service.SittingRecordService;
import city.spring.modules.sitting.vo.SittingRecordVO;
import city.spring.modules.system.entity.UserEntity;
import city.spring.modules.system.mapstruct.SimpleUserVoMapStruct;
import city.spring.modules.system.service.UserService;
import city.spring.modules.system.vo.SimpleUserVO;
import city.spring.utils.BeanUtils;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * Controller：医生坐诊记录
 *
 * @author 侯坤林
 * @date 2020-07-16 15:48:26
 */
@RestController
@RequestMapping("/sitting_record")
public class SittingRecordController extends ApiController {
    private final SittingRecordService sittingRecordService;
    private final OldmanInfoService oldmanInfoService;
    private final UserService userService;
    private final SimpleUserVoMapStruct simpleUserVoMapStruct;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<SittingRecordEntity, ?>> entityOrderFields;

    public SittingRecordController(SittingRecordService sittingRecordService, OldmanInfoService oldmanInfoService, UserService userService, SimpleUserVoMapStruct simpleUserVoMapStruct) {
        this.sittingRecordService = sittingRecordService;
        this.oldmanInfoService = oldmanInfoService;
        this.userService = userService;
        this.simpleUserVoMapStruct = simpleUserVoMapStruct;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(SittingRecordEntity::getId);
        entityOrderFields.add(SittingRecordEntity::getUserId);
        entityOrderFields.add(SittingRecordEntity::getOldmanId);
        entityOrderFields.add(SittingRecordEntity::getDate);
        entityOrderFields.add(SittingRecordEntity::getSymptom);
        entityOrderFields.add(SittingRecordEntity::getDiagnosis);
        entityOrderFields.add(SittingRecordEntity::getSuggest);
        entityOrderFields.add(SittingRecordEntity::getGmtCreated);
        entityOrderFields.add(SittingRecordEntity::getGmtModified);
    }

    /**
     * 获取全部的 <strong>医生坐诊记录</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, SittingRecordEntity entity) {
        LambdaQueryChainWrapper<SittingRecordEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    /**
     * 分页获取 <strong>医生坐诊记录</strong> 列表
     *
     * @param pageable 分页参数信息
     */
    @GetMapping
    public Object list(@PageableDefault Pageable pageable, SittingRecordEntity entity) {
        LambdaQueryChainWrapper<SittingRecordEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        Page<SittingRecordEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
        List<SittingRecordEntity> records = page.getRecords();
        List<SittingRecordEntity> result = new ArrayList<>();
        Map<String, OldmanInfoEntity> oldmanMap = oldmanInfoService.listByIds(records, SittingRecordEntity::getOldmanId, OldmanInfoEntity::getId);
        Map<String, SimpleUserVO> userMap = userService.listByIds(records, SittingRecordEntity::getUserId)
                .stream()
                .map(simpleUserVoMapStruct::toVo)
                .collect(Collectors.toMap(SimpleUserVO::getId, Function.identity()));
        for (SittingRecordEntity record : records) {
            SittingRecordVO vo = BeanUtils.toChildren(record, SittingRecordVO.class);
            vo.setOldman(oldmanMap.get(vo.getOldmanId()));
            vo.setUser(userMap.get(vo.getUserId()));
            result.add(vo);
        }
        page.setRecords(result);
        return success(page);
    }

    /**
     * 获取一个 <strong>医生坐诊记录</strong>
     *
     * @param id 主键ID
     */
    @GetMapping("{id}")
    public Object info(@PathVariable String id) {
        return success(sittingRecordService.getById(id));
    }

    /**
     * 添加一个 <strong>医生坐诊记录</strong>
     *
     * @param entity 修改后的信息
     */
    @PostMapping
    public Object add(@RequestBody SittingRecordEntity entity) {
        sittingRecordService.saveSittingRecord(entity);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
        return new ResponseEntity<>(headers, HttpStatus.CREATED);
    }

    /**
     * 修改一个 <strong>医生坐诊记录</strong>
     *
     * @param id     主键ID
     * @param entity 修改后的信息
     */
    @PutMapping("{id}")
    public Object update(@PathVariable String id, @RequestBody SittingRecordEntity entity) {
        entity.setId(id);
        sittingRecordService.updateSittingRecord(entity);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 删除一个 <strong>医生坐诊记录</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        sittingRecordService.deleteSittingRecord(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>医生坐诊记录</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        sittingRecordService.deleteSittingRecord(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<SittingRecordEntity> buildLambdaQuery(SittingRecordEntity entity) {
        LambdaQueryChainWrapper<SittingRecordEntity> lambdaQuery = sittingRecordService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), SittingRecordEntity::getId, entity.getId());
        if (StringUtils.isNotBlank(entity.getUserId())) {
            Set<String> userIdSet = userService.lambdaQuery().like(UserEntity::getNickname, entity.getUserId()).list().stream().map(UserEntity::getId).collect(Collectors.toSet());
            if (userIdSet.isEmpty()) {
                userIdSet.add(null);
            }
            lambdaQuery.in(SittingRecordEntity::getUserId, userIdSet);
        }
        lambdaQuery.like(StringUtils.isNotBlank(entity.getOldmanId()), SittingRecordEntity::getOldmanId, entity.getOldmanId());
        lambdaQuery.eq(entity.getDate() != null, SittingRecordEntity::getDate, entity.getDate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getSymptom()), SittingRecordEntity::getSymptom, entity.getSymptom());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDiagnosis()), SittingRecordEntity::getDiagnosis, entity.getDiagnosis());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getSuggest()), SittingRecordEntity::getSuggest, entity.getSuggest());
        lambdaQuery.eq(entity.getGmtCreated() != null, SittingRecordEntity::getGmtCreated, entity.getGmtCreated());
        lambdaQuery.eq(entity.getGmtModified() != null, SittingRecordEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<SittingRecordEntity> buildQuery(SittingRecordEntity entity) {
        QueryWrapper<SittingRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getUserId()), "user_id", entity.getUserId());
        wrapper.like(StringUtils.isNotBlank(entity.getOldmanId()), "oldman_id", entity.getOldmanId());
        wrapper.eq(entity.getDate() != null, "date", entity.getDate());
        wrapper.like(StringUtils.isNotBlank(entity.getSymptom()), "symptom", entity.getSymptom());
        wrapper.like(StringUtils.isNotBlank(entity.getDiagnosis()), "diagnosis", entity.getDiagnosis());
        wrapper.like(StringUtils.isNotBlank(entity.getSuggest()), "suggest", entity.getSuggest());
        wrapper.eq(entity.getGmtCreated() != null, "gmt_created", entity.getGmtCreated());
        wrapper.eq(entity.getGmtModified() != null, "gmt_modified", entity.getGmtModified());
        return wrapper;
    }

}
